package top.sheen.platform.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.sheen.framework.core.dto.ReturnInfo;
import top.sheen.framework.core.exception.BusinessException;
import top.sheen.platform.gateway.repository.WechatFansInfoRepository;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author sheen.dong
 * @since 2021/1/27 下午11:56
 */
@Component
public class OrderWechatAuthZuulFilter extends ZuulFilter {

    @Autowired
    private WechatFansInfoRepository wechatFansInfoRepository;
    /**
     * 过滤器的类型有四种：pre route post error
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 通过放回的int值来定义过滤器的优先级，数字越小优先级越高
     * @return
     */
    @Override
    public int filterOrder() {
        return 10;
    }

    /**
     * 判断该过滤器是否会执行（是否执行run方法），放回一个boolean值,true就会执行run方法
     * @return
     */
    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String url = request.getRequestURI();
        if (url.startsWith("/order-wechat")) {
            return true;
        }
        return false;
    }

    /**
     * 过滤器的具体业务逻辑
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        // 初始化context上下文对象，servlet spring
        RequestContext context = RequestContext.getCurrentContext();
        //获取request对象
        HttpServletRequest request = context.getRequest();
        HttpServletResponse response = context.getResponse();
        response.setCharacterEncoding("UTF-8");
        //获取参数
        String openid = request.getHeader("openid");
        if (StringUtils.isBlank(openid)){
            noAuth(response, context);
        }else {
            boolean validIdentity = true;

            try {
                validIdentity = (wechatFansInfoRepository.findFirstByOpenid(openid).orElse(null) != null);
            }catch (BusinessException exception) {
                validIdentity = false;
            }finally {
                // 身份验证不通过
                if (!validIdentity) {
                    noAuth(response, context);
                }
            }
        }
        // 返回值null，就代表该过滤器啥都不做
        return null;
    }

    public void noAuth(HttpServletResponse response, RequestContext context) {
// 如果模拟的登录参数为空，则不转发请求
        context.setSendZuulResponse(false);
        // 响应状态码，401-身份未认证
        context.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
        // 设置响应提示
        ReturnInfo<String> returnInfo = ReturnInfo.error(HttpStatus.SC_UNAUTHORIZED, "没有权限访问", null);
        context.setResponseBody(JSONObject.toJSONString(returnInfo));
    }
}